<template>
  <div class="statistics">
    <el-tabs>
      <el-tab-pane label="调用查询">
        <el-card shadow="never">
          <!-- 搜索 -->
          <el-form :inline="true" :model="orderSearchData" class="demo-form-inline">
            <el-form-item label="订单编号:">
              <el-input style="width:180px" size="small" v-model="orderSearchData.orderCode" placeholder="订单编号查询"
                clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号码:">
              <el-input style="width:130px" size="small" v-model="orderSearchData.mobile" placeholder="手机号查询" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="省份">
              <el-input style="width:130px" size="small" v-model="orderSearchData.province" placeholder="省份查询" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="用户账号:" v-if="this.$store.state.user.role == 'admin'">
              <el-select style="width:130px" size="small" v-model="orderSearchData.username" placeholder="用户账号" clearable>
                <el-option v-for="item in useroptions" :key="item.id" :label="item.username" :value="item.username">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="支付状态:">
              <el-select style="width:130px" size="small" v-model="orderSearchData.stat" clearable placeholder="支付状态">
                <el-option label="成功" value="DELIVRD"> </el-option>
                <el-option label="失败" value="REJECTED"> </el-option>
                <el-option label="等待" value="WAITING"> </el-option>
                <el-option label="交易中" value="SENDING"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运营商:">
              <el-select style="width:130px" size="small" clearable v-model="orderSearchData.operator" placeholder="运营商">
                <el-option label="联通" value="01"> </el-option>
                <el-option label="移动" value="02"> </el-option>
                <el-option label="电信" value="03"> </el-option>
              </el-select>
            </el-form-item>
            <br />
            <el-form-item label="选择日期:">
              <el-date-picker style="width:180px" size="small" v-model="orderSearchData.startTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-date-picker style="width:180px" size="small" v-model="orderSearchData.endTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" plain size="small" @click="searchOrder()">查询</el-button>
              <el-button type="success" icon="el-icon-position" plain size="small" @click="exportExcel()">导出</el-button>
            </el-form-item>
          </el-form>
          <!-- 数据 -->
          <el-table v-loading="loading" id="legacy" ref="orderData" :data="orderData.pageList" tooltip-effect="dark"
            style="width: 100%" border>
            <el-table-column type="index" align="center" width="50">
            </el-table-column>
            <el-table-column prop="createTime" label="调用时间" width="100" align="center">
            </el-table-column>
            <el-table-column label="回调时间" prop="backTime" width="100" align="center">
            </el-table-column>
            <el-table-column prop="orderCode" label="订单编号" width="180" align="center">
            </el-table-column>
            <el-table-column prop="taskId" label="客户编号" width="120" align="center">
            </el-table-column>
            <el-table-column prop="username" label="调用用户" width="120" align="center">
            </el-table-column>
            <el-table-column prop="productId" label="产品编号" width="130" align="center">
            </el-table-column>
            <el-table-column prop="productName" label="调用产品" width="150" align="center">
            </el-table-column>
            <el-table-column label="充值码号" width="120" align="center">
              <template slot-scope="scope">
                <span @click="ckiphone(scope.row.orderCode)">
                  {{
                    scope.row.mobile
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="province" label="省份" width="100" align="center">
            </el-table-column>
            <el-table-column prop="operator" label="运营商" width="100" align="center">
            </el-table-column>
            <!-- <el-table-column label="手机号" width="120" align="center">
              <template slot-scope="scope">
                <span>
                  {{
                    scope.row.mobile.slice(0, 3) +
                      "****" +
                      scope.row.mobile.slice(7, 11)
                  }}
                  </span>
              </template>
            </el-table-column> -->
            <el-table-column label="支付状态" width="100" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.stat == "DELIVRD"
                  ? "成功"
                  : scope.row.stat == "REJECTED"
                    ? "失败"
                    : "交易中"
                }}</span>
              </template>
            </el-table-column>

            <el-table-column align="center" label="回调耗时" width="100">
              <template slot-scope="scope">
                {{ formateTime(scope.row.consumeTime) }}
              </template>
            </el-table-column>


            <el-table-column label="" v-if="this.$store.state.user.role == 'admin'" align="center" width="140">
              <template slot-scope="scope">

                <el-button @click="cghandleClick(scope.row)" type="text" size="small">成功</el-button>
                <el-button @click="sbhandleClick(scope.row)" type="text" size="small">失败</el-button>

              </template>
            </el-table-column>
          </el-table>
          <!-- 手机号查询 -->
          <el-dialog title="订单详情" :visible.sync="iPhonedog" width="50%" :close-on-click-modal=false>

            <span>
              backTime:{{ this.ckiphones.backTime }} <br>
              createTime:{{ this.ckiphones.createTime }} <br>
              message:{{ this.ckiphones.message }} <br>
              params:{{ this.ckiphones.params }} <br>
              result:{{ this.ckiphones.result }} <br>
              stat:{{ this.ckiphones.stat }} <br>
              taskid:{{ this.ckiphones.taskid }} <br>
              unitPrice:{{ this.ckiphones.unitPrice }} <br>
              username:{{ this.ckiphones.username }} <br>

            </span>

            <!-- <json-viewer :value="this.ckiphones"></json-viewer> -->
            <!-- <hr /> -->

            <!-- <json-viewer :value="this.ckiphones" :expand-depth=100 copyable boxed sort></json-viewer> -->
            <!-- <span>{{ JSON.stringify(this.ckiphones) }}</span> -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="iPhonedog = false">取 消</el-button>
              <el-button type="primary" @click="iPhonedog = false">确 定</el-button>
            </span>
          </el-dialog>

          <!-- 分页 -->
          <el-pagination background @size-change="orderSizeChange" @current-change="orderCurrentChange"
            :page-sizes="[10, 50, 100, 1000, 5000, 10000]" :page-size="10" :current-page="orderSearchData.pageNum"
            layout="total, sizes, prev, pager, next, jumper" :total="orderData.totalCount">
          </el-pagination>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="调用统计">
        <el-card shadow="never">
          <!-- 搜索 -->
          <el-form :inline="true" :model="productData2" class="demo-form-inline">
            <el-form-item label="统计方式:">
              <el-select size="small" style="width:140px" v-model="productData2.scope" placeholder="请选择"
                @change="changeSelect2()">
                <el-option label="按天查询" value="day"> </el-option>
                <el-option label="按月查询" value="month"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户账号:" v-if="this.$store.state.user.role == 'admin'">
              <el-select style="width:140px" size="small" v-model="productData2.username" placeholder="用户账号" clearable>
                <el-option v-for="item in useroptions" :key="item.id" :label="item.username" :value="item.username">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运营商:">
              <el-select style="width:130px" size="small" clearable v-model="yysoperator" placeholder="运营商">
                <el-option label="联通" value="01"> </el-option>
                <el-option label="移动" value="02"> </el-option>
                <el-option label="电信" value="03"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择日期:" v-if="timeShow">
              <!-- 按天查询 -->
              <el-date-picker size="small" style="width:180px" v-model="productData2.startTime" type="date"
                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item v-if="timeShow">
              <el-date-picker size="small" style="width:180px" v-model="productData2.endTime" type="date"
                format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <!-- 按月查询 -->
            <el-form-item label="选择月份:" v-if="!timeShow">
              <el-date-picker style="width:150px" size="small" v-model="productData2.startTime" type="month"
                placeholder="选择月份" format="yyyy 年 MM 月" value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="产品编号:">
              <el-input style="width:180px" size="small" v-model="productData2.productId" placeholder="产品编号查询"
                clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" icon="el-icon-search" plain @click="getproductdata2()">查询
              </el-button>
              <el-button type="success" size="small" icon="el-icon-position" plain @click="exportExcel1()">导出
              </el-button>
            </el-form-item>
          </el-form>
          <p style="color: #666; font-size: 8px; text-align: center">
            数据并非实时,页面数据来自1小时前，仅供参考，实际以月末统计账单为准
          </p>
          <div class="card" v-if="subnum">
            <!-- <div class="card" v-if="false"> -->
            <div class="card1">
              <span>成功调用量</span>
              <hr color="#F8F8F8" />
              {{ sdata.success }}次
            </div>
            <div v-if="this.$store.state.user.role == 'admin'" class="card1">
              <span>计费成功调用量</span>
              <hr color="#F8F8F8" />
              {{ sdata.success }}次
            </div>
            <div class="card1">
              <span>失败调用量</span>
              <hr color="#F8F8F8" />
              {{ sdata.error }}次
            </div>
            <br />
            <div class="card1">
              <span>总调用量</span>
              <hr color="#F8F8F8" />
              {{ sdata.all }} 次
            </div>
            <div class="card1">
              <span>总消费[参考值]
                <hr color="#F8F8F8" />
                ￥
              </span>
              {{ sdata.money }}
            </div>

            <div class="card1">
              <span>成功率</span>
              <hr color="#F8F8F8" />
              {{ String(sdata.successPro * 100).slice(0, 5) }}%
            </div>
          </div>
          <!-- 表格内容 -->
          <el-table v-loading="loadingTable1" id="legacy1" ref="multipleTable" :data="ndata2.pageList"
            tooltip-effect="dark" style="width: 100%" border>
            <el-table-column type="index" align="center" width="50">
            </el-table-column>
            <el-table-column label="创建时间" width="120" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px" v-if="timeShow">{{
                  scope.row.createTime
                }}</span>
                <span style="margin-left: 10px" v-if="!timeShow">{{
                  scope.row.createTime.slice(0, 7)
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="120" align="center">
            </el-table-column>
            <el-table-column prop="productId" label="产品编号" width="230" align="center">
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" width="230" align="center">
            </el-table-column>
            <el-table-column prop="clientCount" label="总调用量" align="center">
            </el-table-column>
            <el-table-column label="消费" align="center" width="120">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.consume | currency("￥")
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="successCount" label="成功调用量" align="center">
            </el-table-column>
            <el-table-column prop="errorCount" label="失败调用量" align="center">
            </el-table-column>
            <el-table-column label="运营商" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.operator == '01'">联通</span>
                <span v-if="scope.row.operator == '02'">移动</span>
                <span v-if="scope.row.operator == '03'">电信</span>
                <span v-if="scope.row.operator == null">三网</span>


              </template>
            </el-table-column>



            <el-table-column label="成功率" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.successPro }}%</span>
              </template>
            </el-table-column>
            <el-table-column label="失败率" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.errorPro }}%</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="回调耗时">
              <template slot-scope="scope">
                {{ formateTime(scope.row.consumeTime) }}
              </template>
            </el-table-column>

          </el-table>
          <!-- 分页 -->
          <!-- currentPage -->
          <el-pagination background @size-change="handleSizeChange2" @current-change="handleCurrentChange2"
            :page-sizes="[10, 20, 50, 100]" :page-size="10" :current-page="productData2.pageNum"
            layout="total, sizes, prev, pager, next, jumper" :total="ndata2.totalCount">
          </el-pagination>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="地区数据分析">
        <NumData></NumData>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="成功回执" :visible.sync="okdog" width="30%">
      <!-- <span>请输入密码进行成功回执操作</span> -->
      <span>进行成功回执操作</span>

      <span slot="footer" class="dialog-footer">
        <!-- <el-input placeholder="请输入密码" v-model="okmima" @input="okinput" show-password></el-input> -->
        <el-button @click="okdog = false">取 消</el-button>
        <!-- <el-button type="primary" v-if="okyes" @click="submitok()">确 定</el-button> -->
        <el-button type="primary" @click="submitok()">确 定</el-button>

      </span>
    </el-dialog>


    <el-dialog title="失败回执" :visible.sync="nodog" width="30%">
      <!-- <span>请输入密码进行失败回执操作</span> -->
      <span>进行失败回执操作</span>

      <span slot="footer" class="dialog-footer">
        <!-- <el-input placeholder="请输入密码" v-model="nomima" @input="noinput" show-password></el-input> -->
        <el-button @click="nodog = false">取 消</el-button>
        <!-- <el-button type="primary" v-if="noyes" @click="submitno()">确 定</el-button> -->
        <el-button type="primary" @click="submitno()">确 定</el-button>

      </span>
    </el-dialog>


  </div>
</template>
<script>
import FileSaver from "file-saver";
import * as XLSX from "xlsx";
import { apiScopeCount, orderQuery, getUsername, getBack, getBacksuccessOrder, getBackerrorOrder, getiphoneOrder } from "@/api/order";
import NumData from "./components/numdata.vue"
// 引入防抖函数
import debounce from "lodash.debounce";

export default {
  data() {
    return {
      iPhonedog: false,
      ckiphones: "",
      okmima: "",
      okmimas: "",
      okyes: false,
      nomima: "",
      nomimas: "",
      noyes: false,
      // 回执
      submitokdata: {
        taskid: "",
      },
      // 回执
      submitnodata: {
        taskid: "",
      },
      okdog: false,
      nodog: false,

      useroptions: [],
      sdata: {},
      subnum: false,
      loading: false,
      loadingTable1: false,
      //调用量 搜索条件
      productData: {
        scope: "month",
        startTime: "",
        endTime: "",
      },
      //   数据
      ndata: {},
      //   统计方式
      options: [
        {
          value: "day",
          label: "按天查询",
        },
        {
          value: "month",
          label: "按月查询",
        },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() - 86400000 > Date.now();
        },
      },
      //  详单查询  搜索条件
      orderSearchData: {
        operator: "",
        startTime: "",
        endTime: "",
        province: ""
      },
      //   数据
      orderData: {},
      // 日期显示与隐藏
      timeShow: false,
      //调用量2 搜索条件
      productData2: {
        username: "",
        scope: "month",
        startTime: "",
        endTime: "",
        province: "",
      },
      yysoperator: "",

      //   数据
      ndata2: {},
    };
  },
  components: {
    NumData: NumData
  },
  async created() {


    this.searchOrder();
    this.getproductdata2();
    // let poptions = await getScope();
    // this.poptions = poptions.data;
    // console.log(poptions);
    let username = window.localStorage.getItem("username");
    // this.productData2.username = username;
    let ftime = new Date();
    let a = ftime.getFullYear()
    let b = ftime.getMonth() + 1
    let c = ftime.getDay()
    let ftimes = `${a}-${b}-1 00:00:00`
    this.productData2.startTime = ftimes
    let res = await getUsername({ all: "all" });
    if (res.status == 0) {
      this.useroptions = res.data;
    }
  },
  methods: {
    // 查看手机号
    async ckiphone(r) {
      this.iPhonedog = true
      let sres = await getiphoneOrder(r)
      this.ckiphones = sres.data

      console.log(this.ckiphones);

    },
    formateTime(time) {
      const h = parseInt(time / 3600)
      const minute = parseInt(time / 60 % 60)
      const second = Math.ceil(time % 60)
      const hours = h < 10 ? '0' + h : h
      const formatSecond = second > 59 ? 59 : second
      return `${hours > 0 ? `${hours}时` : ''}${minute < 10 ? '0' + minute : minute}分${formatSecond < 10 ? '0' + formatSecond : formatSecond}秒`
    },

    // 成功回执：
    cghandleClick(row) {
      this.okmima = "";
      this.okyes = false;
      this.okdog = true;
      this.submitokdata.taskid = row.orderCode;
      this.okmimas = row.mobile;
      // console.log(this.okmimas.substring(7, 11));
    },

    // okinput() {
    //   // console.log(this.okmima);
    //   if (this.okmima == this.okmimas.substring(7, 11)) {
    //     this.okyes = true
    //   } else {
    //     this.okyes = false
    //   }
    // },
    // 成功确认





    async submitok() {
      // console.log(this.submitokdata.taskid);
      let data = `taskid=${this.submitokdata.taskid}`;
      let a = await getBacksuccessOrder(data);
      this.$message({
            message: a,
          });
      this.okmima = "";
      this.okdog = false;
      this.okyes = false;
    },
    // 失败回执：
    sbhandleClick(row) {
      this.nomima = "";
      this.noyes = false;
      this.nodog = true;
      this.submitnodata.taskid = row.orderCode;
      this.nomimas = row.mobile;

    },
    // noinput() {
    //   // console.log(this.okmima);
    //   if (this.nomima == this.nomimas.substring(7, 11)) {
    //     this.noyes = true
    //   } else {
    //     this.noyes = false
    //   }
    // },
    // 失败确认
    async submitno() {
      // console.log(2);
      // console.log(this.submitnodata.taskid);
      let data = `taskid=${this.submitnodata.taskid}`;
      let a = await getBackerrorOrder(data);
      this.$message({
            message: a,
          });
      this.nomima = "";
      this.nodog = false;
      this.noyes = false;
    },




    exportExcel() {
      //导出当前表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#legacy")); //表格id
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "详情统计表.xlsx"
        ); //文件名
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    exportExcel1() {
      //导出当前表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#legacy1")); //表格id
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "调用量统计表.xlsx"
        ); //文件名
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 调用量 获取数据
    async priceData() {
      let res = await apiScopeCount(this.productData);
      if (res) {
        this.ndata = res.data;
        console.log("1111", res);
      } else {
        this.ndata = [];
      }
    },
    // 分页查询
    async handleSizeChange(val) {
      this.productData.pageSize = val;
      this.priceData();
    },
    async handleCurrentChange(val) {
      this.productData.pageNum = val;
      this.priceData();
    },
    // 详单查询 获取数据
    async orderSearch() {
      let res = await orderQuery(this.orderSearchData);
      if (res) {
        this.orderData = res.data;
        this.loading = false;

      } else {
        this.orderData = [];
      }
    },
    // 查询
    searchOrder: debounce(function () {
      this.loading = true;
      let startTime = (this.orderSearchData.startTime + "").slice(0, 7);
      let endTime = (this.orderSearchData.endTime + "").slice(0, 7);
      if (
        (this.orderSearchData.startTime && this.orderSearchData.endTime) ||
        (!this.orderSearchData.startTime && !this.orderSearchData.endTime)
      ) {
        if (
          startTime == endTime ||
          !this.orderSearchData.startTime == !this.orderSearchData.endTime
        ) {
          this.orderSearchData.pageNum = 1;
          this.orderSearch();
        } else {
          this.$message({
            message: "不能跨月查询",
            type: "error",
          });
        }
      } else {
        this.$message({
          message: "请输入日期",
          type: "error",
        });
      }
    }, 500),
    // 分页查询
    async orderSizeChange(val) {
      this.orderSearchData.pageSize = val;
      this.orderSearch();
    },
    async orderCurrentChange(val) {
      this.orderSearchData.pageNum = val;
      this.orderSearch();
    },
    // 调用量2 获取数据
    async priceData2() {
      this.loadingTable1 = true;
      this.subnum = false;
      let qq = this.yysoperator
      console.log(qq, 1);
      if (qq != "") {
        let key = "operator";
        let value = qq
        this.productData2[key] = value;
        let res = await apiScopeCount(this.productData2);
        if (res.data) {
          this.subnum = true;
          this.ndata2 = res.data;
          this.sdata = res;
          this.loadingTable1 = false;
          delete this.productData2.operator
        } else {
          this.loadingTable1 = false;
          this.ndata2 = [];
          this.subnum = false;
          delete this.productData2.operator

        }
      } else {
        let res = await apiScopeCount(this.productData2);
        if (res.data) {
          this.subnum = true;
          this.ndata2 = res.data;
          this.sdata = res;
          this.loadingTable1 = false;
        } else {
          this.loadingTable1 = false;
          this.ndata2 = [];
          this.subnum = false;
        }
      }


    },
    // 搜索
    getproductdata2: debounce(function () {
      this.productData2.pageNum = 1;
      this.priceData2();
    }, 500),
    //   下拉框
    changeSelect2() {
      if (this.productData2.scope == "month") {
        this.timeShow = false;
      } else {
        this.timeShow = true;
      }
    },
    // 分页查询
    async handleSizeChange2(val) {
      this.productData2.pageSize = val;
      this.priceData2();
    },
    async handleCurrentChange2(val) {
      this.productData2.pageNum = val;
      this.priceData2();
    },
  },
};
</script>

<style lang="scss" scoped>
.statistics {
  .data {
    display: inline-block;
    height: 40px;
    vertical-align: bottom;
    text-align: center;
    color: rgb(224, 103, 103);
    font-size: 14px;
    box-sizing: border-box;
    margin-left: 10px;
  }
}
</style>
<style scoped>
.card {
  width: 100%;
  text-align: center;
}

.card1 {
  display: inline-block;
  white-space: nowrap;
  width: 33%;
  font-size: 1rem;
  font-family: "Franklin Gothic small", "Arial Narrow", Arial, sans-serif;
  background-color: #fff;
  color: #409eff;
}

.card1 span {
  color: #666;
  font-family: serif;
  font-weight: 600;
}
</style>
<style scoped>
.el-form-item {
  margin-bottom: 0px;
}
</style>
<style>
.el-tabs--top .el-tabs__item.is-top:nth-child(2) {
  padding-left: 20px;
}
</style>